/*
 * @Author: zhangyang
 * @Date: 2021-12-06 18:50:15
 * @LastEditTime: 2021-12-27 17:26:52
 * @Description: 表单相关操作解耦
 */
type Cbk = {
  addCbk?: () => void;
  modCbk?: () => void;
  delCbk?: (row: any) => void;
  cpEffect?: (row: any) => void;
  cgEffect?: () => void;
  disableclear?: boolean;
};
export default <T>(
  FORM_TEMP: T,
  { addCbk, modCbk, delCbk, cpEffect, cgEffect, disableclear }: Cbk,
  tip = '确认删除该条数据？'
) => {
  const isAdd = ref(false);
  const isEdit = ref(false);
  const isMore = ref(false);

  const form = ref<T>(deepClone(FORM_TEMP));

  const clear = () => {
    isAdd.value = false;
    isEdit.value = false;
    isMore.value = false;
    // @ts-ignore
    form.value = deepClone(FORM_TEMP);
  };

  const del = (row: any) => {
    ElMessageBox.confirm(tip, '提示', {
      type: 'warning'
    }).then(async () => {
      await delCbk?.(row);
      cgEffect?.();
    }).catch(() => null);
  };

  const sure = async () => {
    if (isAdd.value) {
      await addCbk?.();
    } else {
      await modCbk?.();
    }
    !disableclear && clear();
    cgEffect?.();
  };

  const edit = (row: any) => {
    form.value = deepClone(row);
    cpEffect?.(row);
    isEdit.value = true;
  };
  const more = (row: any) => {
    form.value = deepClone(row);
    cpEffect?.(row);
    isMore.value = true;
  };
  return {
    isAdd,
    isEdit,
    isMore,
    clear,
    edit,
    more,
    form,
    del,
    sure
  };
};
